﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="VmBins.cs" company="Mar3ek">
//   http://mar3ek.wordpress.com
// </copyright>
// <summary>
//   
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Mar3ek.HouseLight
{
    using System;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Linq;
    using System.Threading;
    using System.Windows;
    using System.Windows.Input;
    using LighthouseNET;

    /// <summary>
    /// Main window view model
    /// </summary>
    public partial class ToolWindowViewModel
    {
        private readonly ICommand _newBinCommand;
        private readonly ICommand _modifyBinCommand;
        private readonly ICommand _deleteBinCommand;
        private bool _isBinsEnabled = true;
        private ObservableCollection<TicketBin> _ticketBins;
        private TicketBin _selectedBin;

        /// <summary>
        /// Gets or sets the ticket bins.
        /// </summary>
        /// <value>
        /// The ticket bins.
        /// </value>
        public ObservableCollection<TicketBin> TicketBins
        {
            get
            {
                return _ticketBins;
            }

            set
            {
                _ticketBins = value;

                OnPropertyChanged(new PropertyChangedEventArgs("TicketBins"));
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether this instance is bins enabled.
        /// </summary>
        /// <value>
        /// <c>true</c> if this instance is bins enabled; otherwise, <c>false</c>.
        /// </value>
        public bool IsBinsEnabled
        {
            get
            {
                return _isBinsEnabled;
            }

            set
            {
                _isBinsEnabled = value;
                OnPropertyChanged(new PropertyChangedEventArgs("IsBinsEnabled"));
            }
        }

        /// <summary>
        /// Gets or sets the selected bin.
        /// </summary>
        /// <value>
        /// The selected bin.
        /// </value>
        public TicketBin SelectedBin
        {
            get
            {
                return _selectedBin;
            }

            set
            {
                _selectedBin = value;
                OnPropertyChanged(new PropertyChangedEventArgs("SelectedBin"));
            }
        }

        /// <summary>
        /// Gets the new bin command.
        /// </summary>
        public ICommand NewBinCommand
        {
            get { return _newBinCommand; }
        }

        /// <summary>
        /// Gets the modify bin command.
        /// </summary>
        public ICommand ModifyBinCommand
        {
            get { return _modifyBinCommand; }
        }

        /// <summary>
        /// Gets the delete bin command.
        /// </summary>
        public ICommand DeleteBinCommand
        {
            get { return _deleteBinCommand; }
        }

        /// <summary>
        /// Refreshes the ticket bins.
        /// </summary>
        private void RefreshBins()
        {
            var t = new Thread(() =>
            {
                try
                {
                    TicketBins = new ObservableCollection<TicketBin>(_api.GetTicketBins(_selectedProject.Id));
                    foreach (var query in TicketBins.Select(b => b.Query))
                    {
                        var query1 = query;
                        Application.Current.Dispatcher.Invoke(new Action(() =>
                                                                             {
                                                                                 if(!SearchKeywords.Contains(query1))
                                                                                 {
                                                                                     SearchKeywords.Add(query1);
                                                                                 }
                                                                             }));
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    IsBinsEnabled = false;
                }
            }) { IsBackground = true, Name = "Refresh ticket bins thread" };
            t.Start();
        }

        /// <summary>
        /// Deletes the specified ticket bin
        /// </summary>
        /// <param name="parameter">The parameter.</param>
        private void DeleteBinAction(object parameter)
        {
            if (parameter == null)
            {
                return;
            }

            var bin = (TicketBin)parameter;

            var result = MessageBox.Show(
                "Do you really want to delete the ticket bin? This action cannot be undone.",
                "HouseLight",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);

            if (result != MessageBoxResult.Yes)
            {
                return;
            }

            try
            {
                _api.DeleteTicketBin(SelectedProject.Id, bin.Id);
                RefreshBins();
            }
            catch (LighthouseResponseException ex)
            {
                MessageBox.Show(
                    ex.Message,
                    "HouseLight",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
            catch (LighthouseServerException ex)
            {
                MessageBox.Show(
                    string.Format("A communication error was encountered. Check your internet connection and try again.\nIf the problem persists, contact the plugin developer.\nError details follow:\n\n{0}", ex.Message),
                    "HouseLight",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// Displays the modify ticket bin window
        /// </summary>
        /// <param name="parameter">The parameter.</param>
        private void ModifyBinAction(object parameter)
        {
            if (parameter == null)
            {
                return;
            }

            var w = new wNewBin(_api, ((TicketBin)parameter)) { Owner = _mainWindow };
            w.Closed += BinWindowClosed;
            w.Show();
        }

        /// <summary>
        /// Displays the new ticket bin window
        /// </summary>
        /// <param name="parameter">The parameter.</param>
        private void NewBinAction(object parameter)
        {
            if (parameter == null)
            {
                return;
            }

            var w = new wNewBin(_api, SelectedProject.Id) { Owner = _mainWindow };
            w.Closed += BinWindowClosed;
            w.Show();
        }

        /// <summary>
        /// Handles the Closed event of a wNewBin window.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BinWindowClosed(object sender, EventArgs e)
        {
            if (((wNewBin)sender).Result)
            {
                RefreshBins();
            }
        }
    }
}
